package com.itheima.stock.service.impl;


import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.domain.*;
import com.itheima.stock.mapper.*;
import com.itheima.stock.pojo.StockBusiness;

import com.itheima.stock.service.StockService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.res.R;



import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockOuterMarketIndexInfoMapper stockOuterMarketIndexInfoMapper;

    @Override
    public List<StockBusiness> getAllStockBusiness() {
        return  stockBusinessMapper.getAll();
    }


    /**
     * 国内大盘指数功能
     * todo
     * @return
     */
    @Override
    public R<List<InnerMarketDomain>> getInnerMarketInfos() {
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now().minusMinutes(1)).toDate();

         //date =DateTime.parse("2022-05-16 10:28:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<String> inner = stockInfoConfig.getInner();
        List<InnerMarketDomain> innerMarkInfosByName = stockMarketIndexInfoMapper.getInnerMarkInfosByName(inner, date);
        return R.ok(innerMarkInfosByName);

    }

    /**
     * 国内板块指数
     * @return
     */
    @Override
    public R<List<StockBlockDomain>> getStockBlockInfos() {
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //Date date =DateTime.parse("2022-01-14 16:57:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockBlockDomain> stockBlockInfos=stockBlockRtInfoMapper.getStockBlockInfos(date);





        return R.ok(stockBlockInfos);
    }

    /**todo
     * 股票涨幅榜功能
     * @return
     */
    @Override
    public R<List<StockUpdownDomain>> getStockUpdownInfos() {
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now().minusMinutes(1)).toDate();
        //Date date =DateTime.parse("2021-12-30 09:42:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockUpdownDomain> stockBlockUpdownInfos=stockBlockRtInfoMapper.getStockUpdownInfos(date);




        return R.ok(stockBlockUpdownInfos);
    }


    /**
     * 外盘
     * @return
     */
    @Override
    public R<List<StockOuterMarketIndexInfoDomain>> getStockOuterMarketIndexInfos() {
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();

        date =DateTime.parse("2021-12-01 10:57:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockOuterMarketIndexInfoDomain>  getStockOuterMarketIndexInfos=stockOuterMarketIndexInfoMapper.getStockOuterMarketIndexInfos(date);
        return R.ok(getStockOuterMarketIndexInfos);
    }

    /**
     * 涨幅榜分页查询功能分析
     * @return
     */
    @Override
    public R<PageResult<StockUpdownDomain>> getStockUpdownInfosByPages(Integer page, Integer pageSize) {
         PageHelper.startPage(page, pageSize);
        List<StockUpdownDomain> stockBlockUpdownAllInfos=stockRtInfoMapper.getStockUpdownAllInfos();
        if (CollectionUtils.isEmpty(stockBlockUpdownAllInfos)) {
            return R.error("暂无数据");
        }
        PageInfo<StockUpdownDomain> stockUpdownDomainPageInfo = new PageInfo<StockUpdownDomain>(stockBlockUpdownAllInfos);
        PageResult<StockUpdownDomain> stockUpdownDomainPageResult = new PageResult<>(stockUpdownDomainPageInfo);
        return R.ok(stockUpdownDomainPageResult);
    }

    /**
     * 涨停跌停数据统计
     * @return
     */
    @Override
    public R<Map> getUpdownCount() {
        Date startTime = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
         startTime = DateTime.parse("2022-01-06 09:25:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
         Date curTime = DateTimeUtil.getCloseDate(DateTime.now()).toDate();
         curTime = DateTime.parse("2022-01-06 14:25:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

         List<Map> upList=stockRtInfoMapper.getUpdownCount(startTime,curTime,1);
         List<Map> downList=stockRtInfoMapper.getUpdownCount(startTime,curTime,0);
       Map<String, List<Map>> HashMap = new HashMap<>();
       HashMap.put("upList",upList);
       HashMap.put("downList",downList);


        return R.ok(HashMap);
    }

    @Override
    public void print(HttpServletResponse response, Integer page, Integer pageSize) {
        try {
            //1.设置响应数据的类型:excel
            response.setContentType("application/vnd.ms-excel");
            //2.设置响应数据的编码格式
            response.setCharacterEncoding("utf-8");
            //3.设置默认的文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("stockRt", "UTF-8");
            //设置默认文件名称
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");

            PageHelper.startPage(page,pageSize);

            List<StockUpdownDomain> stockUpdownAllInfos = stockRtInfoMapper.StockUpdownAll();

            EasyExcel.write(response.getOutputStream(),StockUpdownDomain.class).sheet("股票数据")
                    .doWrite(stockUpdownAllInfos);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * TODO
     * @param code
     * @return
     */
    @Override
    public R<List<Stock4MinuteDomain>> getStock4MinuteDomain(Integer code) {
        Date startTime = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
        startTime = DateTime.parse("2021-12-30 09:25:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date curTime = DateTimeUtil.getCloseDate(DateTime.now()).toDate();
        curTime = DateTime.parse("2021-12-30 14:25:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        List<Stock4MinuteDomain> Stock4MinuteDomain= stockRtInfoMapper.getStock4MinuteDomain(code,startTime,curTime);
           return R.ok(Stock4MinuteDomain);

    }
    /**
     * 股票成交量对比
     * @param
     * @return
     */
    @Override
    public R<Map> getTodayPreDayInfos() {
        //今天的开始结束时间
        Date TstartTime = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
        Date TcurTime = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //假数据
        TstartTime = DateTime.parse("2022-01-03 09:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        TcurTime = DateTime.parse("2022-01-03 14:40:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

       //昨天的开始结束时间
        Date PstartTime = DateTimeUtil.getOpenDate(DateTimeUtil.getPreviousTradingDay(DateTime.now())).toDate();
        Date PcurTime = DateTimeUtil.getPreviousTradingDay(DateTime.now()).toDate();
        //假数据
        PstartTime = DateTime.parse("2022-01-02 09:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        PcurTime = DateTime.parse("2022-01-02 14:40:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       //市场代码
        List<String> inner = stockInfoConfig.getInner();


        List<Map> TodayInfos= stockMarketIndexInfoMapper.getTodayPreDayInfos(TstartTime,TcurTime,inner);

        List<Map> PredayInfos= stockMarketIndexInfoMapper.getTodayPreDayInfos(PstartTime,PcurTime,inner);
        Map<String,List<Map>> map=new HashMap<>();
        map.put("volList",TodayInfos);
        map.put("yesVolList",PredayInfos);


        return R.ok(map);
    }


    /**
     * 个股涨幅幅度
     * todo
     * @return
     */
    @Override
    public R<Map> getRangeCountByMinutes() {
        //
        DateTime dateTime=DateTimeUtil.getLastDate4Stock(DateTime.now().minusMinutes(1));
        Date date = dateTime.toDate();
       // date =DateTime.parse("2021-12-31 14:58:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Map> RangeCountByMinutesInfo=stockRtInfoMapper.getRangeCountByMinutes(date);
        List<String> inner =stockInfoConfig.getUpDownRange();
        List<Map> maps=new ArrayList<>();
        for (String s : inner) {
            Map tmp=null;
            for (Map r : RangeCountByMinutesInfo) {
               if(r.get("title").equals(s)){
                   tmp=r;
                   break;
               }
               if(tmp==null){
                   tmp=new HashMap();
                   tmp.put("title",s);
                   tmp.put("count",0);
               }
            }  maps.add(tmp);
        }
        Map ResultMap=new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String dateStr = sdf.format(date);
        ResultMap.put("time",dateStr);
        ResultMap.put("infos",maps);
        return R.ok(ResultMap);

//
//        List<Map> orderMap = inner.stream().map(( key) -> {
//            Optional<Map> title = maps.stream().filter(map -> key.equals(map.get("title"))).findFirst();
//            //判断对应的map是否存在
//            Map tmp = null;
//            if (title.isPresent()) {
//                tmp = title.get();
//            } else {
//                tmp = new HashMap();
//                tmp.put("title", key);
//                tmp.put("count", 0);
//            }
//            return tmp;
//        }).collect(Collectors.toList());
    }

    /**
     * 个股日K线
     * @param code
     * @return
     */
    @Override
    public R<List<Stock4EvrDayDomain>> getStock4EvrDayDomain(String code) {
        //今天的开始结束时间
        Date TcurTime = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //假数据
        TcurTime = DateTime.parse("2022-03-21 15:00:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        //昨天的开始结束时间
        Date PstartTime = DateTimeUtil.getOpenDate(new DateTime().minusDays(10)).toDate();
        //假数据
        PstartTime = DateTime.parse("2021-12-30 09:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Stock4EvrDayDomain> stock4EvrDayDomain = stockRtInfoMapper.getStock4EvrDayDomain(TcurTime, PstartTime, code);

        return R.ok(stock4EvrDayDomain);
    }

    @Override
    public R<List<Map>> getFuzzyQueryStockCode(String searchStr) {
        List<Map> FuzzyQueryStockCode= stockBusinessMapper.getFuzzyQueryStockCode(searchStr);



        return R.ok(FuzzyQueryStockCode);
    }

    @Override
    public R<Map> getStockDescribe(String code) {
        Map StockDescribeInfos=stockBusinessMapper.getStockDescribe(code);

        return R.ok(StockDescribeInfos);
    }

    /**
     * 股票细节信息
     * @param code
     * @return
     */
    @Override
    public R<StockDetailBySecondDomain> getStockDetailBySecond(String code) {
        Date curDate = DateTimeUtil.getLastDate4Stock(new DateTime()).toDate();
       // curDate = DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        StockDetailBySecondDomain StockDetailBySecondInfo=  stockRtInfoMapper.getStockDetailBySecondInfo(code ,curDate);

        return R.ok(StockDetailBySecondInfo);
    }


}
